package com.android.djlmapp.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.ForgetPwdActivity;
import com.android.djlmapp.activity.kaika.web.LianTongXieYiListActivity;
import com.android.djlmapp.activity.kaika.web.PaySuccessActivity;
import com.android.djlmapp.activity.order.OrderListActivity;
import com.android.djlmapp.activity.recharge.AddMoneyActivity;
import com.android.djlmapp.adapter.dialog.GetSimNumAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.listener.LocationCallBack;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.model.home.LocationInfo;
import com.android.djlmapp.model.kaika.SimNumInfo;
import com.android.djlmapp.popupwindow.CommonPopupWindow;
import com.android.djlmapp.tools.global.Constants;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.GlobalUtils;
import com.android.djlmapp.tools.global.MD5Util;
import com.android.djlmapp.tools.global.MyActivityManager;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ChengKaJiHuoActivity extends BaseActivity {


    @BindView(R.id.top_bac)
    ImageView topBac;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;

    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.tv_sim)
    TextView tvSim;
    @BindView(R.id.sim_num)
    EditText simNum;
    @BindView(R.id.tv_sys)
    TextView tvSys;
    @BindView(R.id.xhrz_cl_sim)
    ConstraintLayout xhrzClSim;
    @BindView(R.id.tv_xzhm)
    TextView tvXzhm;
    @BindView(R.id.kk_tv_xzhm)
    TextView kkTvXzhm;
    @BindView(R.id.cl_select_num)
    ConstraintLayout clSelectNum;
    @BindView(R.id.tv_smrz)
    TextView tvSmrz;
    @BindView(R.id.kk_tv_smrz)
    TextView kkTvSmrz;
    @BindView(R.id.cl_shiming)
    ConstraintLayout clShiming;
    @BindView(R.id.tv_smname)
    TextView tvSmname;
    @BindView(R.id.kk_tv_name)
    TextView kkTvName;
    @BindView(R.id.kk_cl_name)
    ConstraintLayout kkClName;
    @BindView(R.id.tv_cardnum)
    TextView tvCardnum;
    @BindView(R.id.kk_tv_cardnum)
    TextView kkTvCardnum;
    @BindView(R.id.kk_cl_cardnum)
    ConstraintLayout kkClCardnum;
    @BindView(R.id.kk_iv_photo)
    ImageView kkIvPhoto;
    @BindView(R.id.cl_smrz_item)
    ConstraintLayout clSmrzItem;
    @BindView(R.id.tv_lxhm)
    TextView tvLxhm;
    @BindView(R.id.ll_tv_lxhm)
    EditText llTvLxhm;
    @BindView(R.id.kk_qianming_photo)
    ImageView kkQianmingPhoto;
    @BindView(R.id.cl_qianming)
    ConstraintLayout clQianming;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.tv_ltxy)
    TextView tvLtxy;
    @BindView(R.id.ckjh_scroll)
    ScrollView scroll;
    @BindView(R.id.kk_tv_submit)
    TextView kkTvSubmit;

    private String jiTuanNum = ""; // 集团编码
    private String heYueId = ""; // 合约id
    private String imeiNo = ""; // imei号
    private String yeWuType = ""; // 开界面传过来,业务类型
    private String addPara = ""; // addPara


    private String selectPhoneNum = ""; // 选择的号码
    private String bluetoothName = ""; // 蓝牙设备名称
    private String specId = "";
    private String sName = ""; // 签名url
    private String sFlag = "";  // 是否签名
    private String sMoney = ""; // 签名带回的金额
    private String keyvalue = ""; // SIM卡输入内容
    private int phot_lists = 0; // 用户上传的照片(正,反,手持,公安)

    private CommonPopupWindow window;
    private ListView popList;
    private GetSimNumAdapter popAdapter;
    private CommonPopupWindow.LayoutGravity layoutGravity;
    private PopupWindow popupWindow;
    private ArrayList<SimNumInfo.IccidListBean> simlist = new ArrayList<>();
    private StringBuilder stringBuilder;
    private String face_image = "";
    private String face_ok = "";
    private String sfz_card = "";
    private String sfz_name = "";
    private String sfzPhoto = "";
    private String typeId = "";
    private String paySucUrl = "";
    private String hzAddress = "";
    private String hzTime = "";
    private String hzSex = "";
    private String idcardType = "1";
    private boolean isShow = false; // 防止获取不到位置重复显示键盘
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (passwordDialog != null) {
                passwordDialog.dismiss();
            }
            EventBusUtil.sendEvent(new Event<String>(EventCodes.EventKaiKaCode.D));
            switch (msg.what) {
                case 0:
                    // 跳转订单页
                    startActivity(new Intent(ChengKaJiHuoActivity.this, OrderListActivity.class));
                    finish();
                    break;
                case 1:
                    // 跳转web转订单
                    Intent intent1 = new Intent(ChengKaJiHuoActivity.this,
                            PaySuccessActivity.class);
                    intent1.putExtra("sucUrl", paySucUrl);
                    startActivity(intent1);
                    finish();
                    break;
            }
        }
    };
    private String phoneNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chengkajihuo);
        ButterKnife.bind(this);
        initView();
        initData();
        creatPopupWindow(); // 创建SIM卡窗口
    }

    @Override
    protected void initView() {
        PrefUtils.putString("FACE_TOKEN", ""); // 置空新活体检测保存的数据

        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("成卡激活");
        tvXzhm.setText("绑定号码");

        // 业务类型
        yeWuType = getIntent().getStringExtra("YEWUTYPE");
    }

    @Override
    protected void initData() {
        stringBuilder = new StringBuilder();

        simNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    if (simlist != null && simlist.size() > 0) {
                        simlist.clear();
                        //要先让popupwindow获得焦点，才能正确获取popupwindow的状态
//                        popupWindow.setFocusable(true);
                        // popupwindow处于显示状态,可以关闭
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                    }
                }
            }
        });

        simNum.addTextChangedListener(phoneTextW);  //监听输入框变化
        simNum.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e("项目异常ACTION_UP", "------ACTION_UP------" + simlist.size());
                        if (simlist != null && simlist.size() > 0) {
                            simlist.clear();
                            //要先让popupwindow获得焦点，才能正确获取popupwindow的状态
//                    popupWindow.setFocusable(true);
                            // popupwindow处于显示状态,可以关闭
                            if (popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }
                        } else {
                            keyvalue = simNum.getText().toString().trim();
                            if (TextUtils.isEmpty(keyvalue)) {
                                keyvalue = "";
                            }
                            // 处于关闭状态,可以显示
                            window.showBashOfAnchor(simNum, layoutGravity, 0, 0);
                            getSimNumData(keyvalue);
                        }
                        scroll.requestDisallowInterceptTouchEvent(true);
                        break;
                }
                return false;
            }
        });

    }

    @OnClick({R.id.tv_sys, R.id.cl_shiming,
            R.id.cl_qianming, R.id.tv_ltxy, R.id.kk_tv_submit})
    public void onViewClicked(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        switch (view.getId()) {

            case R.id.tv_sys: // 扫一扫
                Intent intent = new Intent(ChengKaJiHuoActivity.this,
                        TiaoXingCodeScanerActivity.class);
                startActivityForResult(intent, 0);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
                break;

            case R.id.kk_eye: // 眼睛
                break;
            case R.id.cl_shiming: //实名认证
                selectPhoneNum = kkTvXzhm.getText().toString().trim();
                if (!TextUtils.isEmpty(selectPhoneNum)) {

                    startActivity(new Intent(ChengKaJiHuoActivity.this, ShiMingRengZhengActivity.class)
                            .putExtra("SPECID", specId).putExtra("selectPhoneNum", selectPhoneNum));
                } else {
                    ToastUtils.showShortToast(ChengKaJiHuoActivity
                            .this, "请先选择号码");
                }

                break;
            case R.id.cl_qianming: // 签名
                startActivityForResult(new Intent(ChengKaJiHuoActivity.this, QianMingActivity.class), 0);
                break;
            case R.id.tv_ltxy: // 联通协议
                // 联通协议
                startActivity(new Intent(ChengKaJiHuoActivity.this,
                        LianTongXieYiListActivity.class));
                break;
            case R.id.kk_tv_submit: // 提交
                isShow = false;
                kkTvSubmit.setEnabled(false);
                if (isSubmit()) {
                    ChengKaJiHuoActivityPermissionsDispatcher.openCameraWithCheck(this);
                } else {
                    kkTvSubmit.setEnabled(true);
                }
                break;
        }
    }

    /**
     * 判断是否需要跳转界面
     */
    private void getSimNumData(String editValue) {
        if (isJump) {
            // 如果是跳转界面就在点击完成后禁用点击事件
            kkTvXzhm.setEnabled(false);
        }
        MyApplication.getInstance().getHttpTools().getSimNum("", "", addPara, editValue, yeWuType,
                new StringCallback() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("项目异常", "------1------" + "");
                        try {
                            parseSimNumJson(response.body(), isJump);
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (popupWindow != null && popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }
                            ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                        ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        kkTvXzhm.setEnabled(true);
                    }
                });
    }

    /**
     * @param json
     * @param isJump 判断是否需要跳转界面
     */
    private void parseSimNumJson(String json, boolean isJump) {
        Log.e("项目异常", "------parseSimNumJson------" + json);
        Gson gson = new Gson();
        SimNumInfo simNumInfo = gson.fromJson(json, SimNumInfo.class);
        if (simNumInfo != null) {
            int code = simNumInfo.getCode();
            if (code == 300) {
                simlist.clear(); // 每次输入的时候，重新初始化数据列表
                simlist.addAll(simNumInfo.getIccid_list()); // 添加SIM卡数据
                if (simlist != null && simlist.size() > 0) {
                    if (isJump) {
                        yanZhengSimNum(); // 验证sim卡号
                    } else {
                        popAdapter.setData(simlist);
                    }
                } else {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "未检测到可用SIM卡");
                }
            } else {
                ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                        simNumInfo.getMsg());
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        } else {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "未获取到数据");
        }
    }

    /**
     * 验证sim卡号
     */
    private void yanZhengSimNum() {
        for (SimNumInfo.IccidListBean entity : simlist) {
            stringBuilder.append(entity.getKey() + entity.getNum());
        }
        if (stringBuilder.toString().contains(keyvalue)) {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            Log.e("项目异常simNum", "------yanZhengSimNum------" + keyvalue);

            Intent intent = new Intent(ChengKaJiHuoActivity.this
                    , ShiMingRengZhengActivity.class);
            intent.putExtra("CHENGKAJIHUO", 3);
            intent.putExtra("SPECID", "");
            intent.putExtra("selectPhoneNum", selectPhoneNum);
            startActivity(intent);
        } else {
            ToastUtils.showShortToast(ChengKaJiHuoActivity
                    .this, "该SIM卡不可用");
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        // 注册eventbus
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        // 接受到Event后的相关逻辑
        switch (event.getCode()) {
            case EventCodes.EventFaceCode.A: // 实名认证
                phot_lists = PrefUtils.getInt("PHOT_LISTS", 0); // 用户上传的照片(正,反,手持,公安)
                FaceRzInfo data3 = (FaceRzInfo) event.getData();
                if (data3 != null) {
                    face_image = data3.getFace_image();
                    face_ok = data3.getFace_ok();
                    sfz_card = data3.getSfz_card();
                    sfz_name = data3.getSfz_name();
                    sfzPhoto = data3.getSfzPhoto();
                    hzAddress = data3.getAddress();
                    hzTime = data3.getTime();
                    hzSex = data3.getSex();

                    if (!TextUtils.isEmpty(hzAddress) && !TextUtils.isEmpty(hzTime) && !TextUtils.isEmpty(hzSex)) {
                        idcardType = "2";
                    }

                    if (!"1".equals(face_ok) && !"2".equals(face_ok)) {
                        kkTvSmrz.setText("请扫描进行认证");
                        clSmrzItem.setVisibility(View.GONE);
                        return;
                    }

                    if ("1".equals(face_ok)) {
                        kkTvSmrz.setText("已认证");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else if ("2".equals(face_ok)) {
                        kkTvSmrz.setText("待审核");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    }

                    clSmrzItem.setVisibility(View.VISIBLE);

                    kkTvSmrz.setTextColor(Color.BLACK);
                    kkTvName.setText(sfz_name);
                    kkTvCardnum.setText(sfz_card);
                    // 加载身份证照片
                    if (!TextUtils.isEmpty(sfzPhoto)) {
                        Glide.with(ChengKaJiHuoActivity.this).load(sfzPhoto).into(kkIvPhoto);
                    } else {
                        kkIvPhoto.setImageBitmap(null);
                    }
                }

                break;
        }
    }

    //点击返回键，返回上一个页面，而不是退出程序
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            FaceRzInfo faceRzInfo = new FaceRzInfo();
            faceRzInfo.setFace_ok(""); // 认证结果 1 成功  2 失败
            Event<FaceRzInfo> events = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
            EventBusUtil.sendEvent(events);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        simlist.clear(); // 防止触摸判断的时候不显示弹窗
    }

    /**
     * 判断能否提交订单
     */
    private boolean isSubmit() {
        boolean isSubMit = false;
        phoneNum = kkTvXzhm.getText().toString().trim();
        String trim = llTvLxhm.getText().toString().trim();

        if (!TextUtils.isEmpty(phoneNum)) {

            if (!TextUtils.isEmpty(sfz_card) && sfz_card != null) {
                if (!TextUtils.isEmpty(trim)) {
                    boolean matches = TextUtils.isDigitsOnly(trim);
                    Log.e("项目异常matches", trim.length() + "------matches------" + matches);
                    if (matches && trim.length() == 11) {
                        if ("1".equals(sFlag)) {
                            // 先判断权限
                            // showContacts();
                            if (cbXieyi.isChecked()) {
                                isSubMit = true;
                            } else {
                                ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                                        "请阅读开卡相关协议并同意");
                            }
                        } else {
                            ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                                    "请先签名");

                        }
                    } else {
                        ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                                "联系电话格式有误");
                    }

                } else {
                    ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                            "请输入联系电话");
                }
            } else {
                ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                        "请先实名认证");
            }
        } else {
            ToastUtils.showShortToast(ChengKaJiHuoActivity.this,
                    "请先选择号码");
        }
        return isSubMit;

    }


    /**
     * 提交订单
     */
    private void submitOrder(String password, String touch_pwd, String touch_num) {
        String jbr_idnum = PrefUtils.getString("JBR_IDNUM", ""); // 获取经办人身份证号
        String face_token = PrefUtils.getString("FACE_TOKEN", ""); // 获取新活体检测数据
        String mobile = llTvLxhm.getText().toString().trim(); // 联系号码
        MyApplication.getInstance().getHttpTools().submitKaiKa(hzTime, idcardType, hzSex, hzAddress,
                sfz_name, phot_lists, "", addPara, mobile, bluetoothName, face_image, face_ok,
                face_token, longitude + "", latitude + "", keyvalue, selectPhoneNum, imeiNo, heYueId,
                jiTuanNum, jbr_idnum, specId, typeId, sfz_card, sfz_name, sName, password, touch_pwd,
                touch_num, yeWuType, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parseSubmitJson(response.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                            passwordDialog.setState(R.mipmap.pay_er, "支付失败1");
                            ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "数据解析异常");
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        // 显示支付失败
                        passwordDialog.setState(R.mipmap.pay_er, "支付失败2");
                        ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

    }

    private void parseSubmitJson(String json) {
        Gson gson = new Gson();
        Info info = gson.fromJson(json, Info.class);

        if (info != null) {
            int code = info.getCode();
            if (TextUtils.isEmpty(info.getMsg())) {
                passwordDialog.setState(R.mipmap.pay_er, "提交失败:" + code);
                return;
            }
            if (code < 1000) { // web
                // 显示支付成功
                passwordDialog.setState(R.mipmap.pay_su, "支付成功");
                paySucUrl = info.getUrl();

                handler.sendEmptyMessageDelayed(1, 1000);

            } else if (code > 6999 && code < 8001) {
                // 跳到订单界面
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());

                handler.sendEmptyMessageDelayed(0, 1000);
            } else if (code == 3001) {
                // 显示订单提交失败
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());
            } else {
                // 显示订单提交失败
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());

            }
        } else {
            passwordDialog.setState(R.mipmap.pay_er, "提交返回数据为空");
        }
    }

    private boolean isJump = false;

    /**
     * 跳转扫描界面之后带回的结果
     * requestCode:请求码
     * resultCode:响应码
     * data:返回的Bundle数据捆
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0:
                if (data != null) {
                    Bundle str = data.getExtras();
                    if (str != null) {
                        String result = str.getString(CodeUtils.RESULT_STRING);
                        int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                        switch (resultType) {
                            case CodeUtils.RESULT_SUCCESS:
                                if (result != null) {
                                    if (result.length() == 19) {
                                        keyvalue = result.substring(0, 19);
                                        if (TextUtil.isNumeric(keyvalue)) {
                                            // 是纯数字
                                            simNum.setText(keyvalue);

                                            isJump = true;
                                        } else {
                                            ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "请确定您扫描的是SIM卡1");
                                            kkTvXzhm.setText("");
                                        }
                                    } else {
                                        ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "请确定您扫描的是联通SIM卡");
                                        kkTvXzhm.setText("");
                                    }
                                } else {
                                    ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "扫描失败，请重新扫描1");
                                }
                                break;
                            case CodeUtils.RESULT_FAILED:
                                ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "扫描失败，请重新扫描2");
                                break;
                        }
                    }
                }
                break;
            case 2:
                if (data != null) {
                    // 签名url
                    sName = data.getStringExtra("fileName");
                    // 是否签名
                    sFlag = data.getStringExtra("signFlag");
                    // 签名带回的金额
                    sMoney = data.getStringExtra("signMoney");

                    Log.e("项目异常", "----getStringExtra--sMoney------" + sMoney);
                    Log.e("项目异常", "----getStringExtra--sName------" + sName);

                    if (!TextUtils.isEmpty(sName)) {
                        // 加载签名照片
                        ImageLoader.getInstance()
                                .displayImage(sName, kkQianmingPhoto, new DisplayImageOptions.Builder()
                                        .cacheInMemory(true)//默认会在内存缓存
                                        .cacheOnDisk(true)//默认会在硬盘缓存
                                        .displayer(new FadeInBitmapDisplayer(1000)).build());
                    }
                } else {
                    ToastUtils.showShortToast(ChengKaJiHuoActivity.this, "未获取到签名");
                }
                break;
        }
    }

    /**
     * 创建popupwindow
     * https://www.cnblogs.com/jzyhywxz/p/7039503.html
     */
    private void creatPopupWindow() {
        int PopWidth = GlobalUtils.getScreenWidth(ChengKaJiHuoActivity.this);
        int PopHeight = GlobalUtils.getScreenHeight(ChengKaJiHuoActivity.this);
        PopWidth = (int) Math.rint(PopWidth / 1.6);
        PopHeight = (int) Math.rint(PopHeight / 2.2);
        window = new CommonPopupWindow(ChengKaJiHuoActivity.this, R.layout.pop_select_list,
                PopWidth, PopHeight) {
            @Override
            protected void initView() {
                View contentView = getContentView();
                popList = contentView.findViewById(R.id.pop_list);
                popAdapter = new GetSimNumAdapter(ChengKaJiHuoActivity.this);
                popAdapter.setData(simlist);
                popList.setAdapter(popAdapter);
            }

            @Override
            protected void initEvent() {
                popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (simlist != null && simlist.size() > 0) {
                            String iccidNum = simlist.get(position).getNum();// SIM卡号
                            selectPhoneNum = simlist.get(position).getDuan();
                            simNum.setText(iccidNum);
                            kkTvXzhm.setText(selectPhoneNum);

                            yanZhengSimNum();
                        }
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();

            }
        };
        popupWindow = window.getPopupWindow();

        // 防止键盘影响
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                return true;
            }
        });
        /**
         * 触摸popwindow 隐藏弹出框
         */
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                simlist.clear();
            }
        });
        // 设置显示位置属性
        layoutGravity = new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.CENTER_HORI
                | CommonPopupWindow.LayoutGravity.TO_BOTTOM);

//        window.showBashOfAnchor(view, layoutGravity, 0, 0); // 显示在控件下方
    }

    private double latitude = 0; // 纬度
    private double longitude = 0; // 经度
    private DJLM_PasswordDialog passwordDialog;

    /**
     * 初始化密码键盘
     */
    private void initKeyBord() {
        passwordDialog = new DJLM_PasswordDialog(ChengKaJiHuoActivity.this);
        passwordDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, String pwd) {
                passwordDialog.showLoadingView();
                submitOrder(pwd, "", "");
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
                passwordDialog.showLoadingView();
                String touch_pwd = PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, "");
                String num = (System.currentTimeMillis() + "").substring(3);
                String newpwd = MD5Util.MD5("DJLM_TOUCH_PAY" + num +
                        UserInfoUtils.getUserInfoUtilsInstance().getToken() + touch_pwd).toLowerCase();
                submitOrder(Constants.getZhiWenNewPwd(ChengKaJiHuoActivity.this),
                        Constants.getZhiWenTouchPwd(ChengKaJiHuoActivity.this),
                        Constants.zhiWenNum);
            }

            @Override
            public void onBtnClick(int type) {
                if (type == 1) {
                    //加款按钮点击
                    startActivity(new Intent(ChengKaJiHuoActivity.this, AddMoneyActivity.class));
                } else if (type == 2) {
                    //忘记密码按钮点击
                    startActivity(new Intent(ChengKaJiHuoActivity.this, ForgetPwdActivity.class));
                }
            }
        });
    }

    /**
     * 弹出自定义输入键盘
     */
    private void showKeyBoard() {
        kkTvSubmit.setEnabled(true);
        initKeyBord(); // 初始化密码键盘
        passwordDialog.show(getSupportFragmentManager(), "支付");
        if (PrefUtils.getBoolean(ConstantsValue.ZHIWEN_STATE, false)
                && !TextUtils.isEmpty(PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, ""))) {
            if (passwordDialog.isFingerprintEnable()) {
                passwordDialog.setEnableFinger(true);
            } else {
                passwordDialog.setEnableFinger(false);
            }

        } else {
            passwordDialog.setEnableFinger(false);
        }
        //设置余额
        passwordDialog.setYue(sMoney);
    }

    TextWatcher phoneTextW = new TextWatcher() { // EditText变化监听

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.e("项目异常simNum", "------afterTextChanged------" + s.toString());

            keyvalue = simNum.getText().toString();

            //将光标移至文字末尾
            simNum.setSelection(keyvalue.length());
//            if (!TextUtils.isEmpty(keyvalue)) {
                boolean activityExist = MyActivityManager.isActivityExist(getActivity());
                Log.e("项目异常", "-----activityExist------" + activityExist);
                if (activityExist) {
                    if (window != null) {
                        window.showBashOfAnchor(simNum, layoutGravity, 0, 0);
                        getSimNumData(keyvalue);
                    }
                }
//            } else {
//                if (popupWindow != null && popupWindow.isShowing()) {
//                    popupWindow.dismiss();
//                }
//            }
        }
    };

    @Override
    protected void onDestroy() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }
    //=======================================请求定位权限=======================================

    /**
     * 获取位置信息
     */
    private void getLocationPrem() {
        showKeyBoard();
        // 获取经纬度
        try {
            OnceLocationTools locationTools = new OnceLocationTools(ChengKaJiHuoActivity.this,
                    new LocationCallBack() {
                        @Override
                        public void successGetLocation(LocationInfo info) {
                            //定位成功
                            latitude = info.getLatitude();
                            longitude = info.getLongitude();
                        }

                        @Override
                        public void error(String error) {
                            latitude = 0.0;
                            longitude = 0.0;
                            if (!isShow) {
                                isShow = true; // 第一次进入就改变状态,防止再次进入,在点击的时候重置状态
                            }
                        }
                    });
            locationTools.startLocation();//开始定位
        } catch (NullPointerException ex) {
            latitude = 0.0;
            longitude = 0.0;
        }
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        getLocationPrem();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ChengKaJiHuoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "denied权限: =================");
                getLocationPrem();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        Log.e("权限", "------askAgain------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "askAgain权限: =================");
                getLocationPrem();
            }
        });
    }
}

